
#include "Request.h"
#include <time.h>
#include <stdio.h>
#include	<sstream>
Request::Request()
{

}

Request::~Request()
{

}
using namespace std;
void				Request::traitHEAD(std::string p, zia::api::DataTree& data)
{
	std::ifstream		infile;
	struct				tm Today;
	time_t				maintenant;
	std::ostringstream	s;
	int					length = 0;

	time(&maintenant);
	Today = *localtime(&maintenant);

	infile.open(p.c_str() + 1, std::ifstream::in); // Flop a decale' le pointer pour virer le '/' du debut
	if (infile.is_open())
	{
		infile.seekg(0, std::ios::end);
		length = infile.tellg();
		infile.seekg(0, std::ios::beg);
		data["version"] = "HTTP/1.1";
		data["code"] = "200";
		data["msg"] = "OK";
		infile.close();
	}
	else
	{
		length = 0;
		data["version"] = "HTTP/1.1";
		data["code"] = "404";
		data["msg"] = "NOT FOUND";
	}
	s << Today.tm_mday << " " << Today.tm_mon + 1 << " " << Today.tm_year + 1900 << " " << Today.tm_hour << ":" << Today.tm_min << ":" << Today.tm_sec << " GMT";
	data["date"] = s.str();
	data["server"] = "ZiaTamer";
	data["connection"] = "Keep Alive";
	cout << "BEFORE GETEXT" << endl;
	
	if (this->getExt(p) == "txt")
		data["type"] = "text/txt";
	else if (this->getExt(p) == "html")
		data["type"] = "text/html";
	else if (this->getExt(p) == "xml")
		data["type"] = "application/xml";
	else if (this->getExt(p) == "png")
		data["type"] = "image/png";
	else if ((this->getExt(p) == "jpeg") || (this->getExt(p) == "jpg"))
		data["type"] = "image/jpeg";
	else if (this->getExt(p) == "gif")
		data["type"] = "image/gif";
	else if (this->getExt(p) == "bmp")
		data["type"] = "image/x-xbitmap";
	
	std::ostringstream	tmp;
	tmp << length;
	data["length"] = tmp.str().c_str();
	
}

std::string				Request::traitGET(std::string p, zia::api::DataTree& data)
{
	std::ifstream		infile;
	std::ostringstream	buffer;
	std::string str;
	char c;
	
	this->traitHEAD(p, data);
	
	infile.open(p.c_str() + 1, std::ifstream::binary);
	while (infile.good())
	  {
	    c = infile.get();
	    if (infile.good())
	      buffer << c;
	  }
	infile.close();
	return buffer.str();
}

void		Request::traitPOST(std::string p)
{
	std::string contenu("blobloooooooooi\n");

	std::ofstream outfile(p.c_str(), std::ofstream::binary);

	outfile << contenu;
}


void		Request::traitDELETE(std::string p)
{
	remove(p.c_str());
}


std::string	Request::getExt(std::string p)
{
	std::string ret = "";
	int	x;
	for (x = 0; p[x] != '.' && p[x] != '\0'; x++);
	x++;
	while ((x < int(p.size())) && (p[x] != '\0') && (p[x] != '?'))
	{
		ret += p[x];
		++x;
	}
	return ret;
}
